#!/bin/sh
#
# Starts gateway  .
#
OTA_FILE="/root/gateway.update"
BAK_FILE="/root/gateway_bak"
EXE_FILE="/usr/bin/gateway"

start() {

    #替换程序  
    #判断是否存在 文件 gateway.update
    if [ -f $OTA_FILE ] 
    then
    #如果存在  
    #先把历史备份 删除 
        rm -f $BAK_FILE
    #把旧程序文件 作为历史备份重命名
        mv $EXE_FILE $BAK_FILE
    #把下载好的文件重命名为正式文件
        mv $OTA_FILE $EXE_FILE
    # 加执行权限
        chmod +x $EXE_FILE
    fi
	printf "Starting gateway: "
 
	start-stop-daemon -S -q -p /var/run/gateway.pid \
		--exec $EXE_FILE -- daemon >/dev/null 2>1&
	[ $? = 0 ] && echo "OK" || echo "FAIL"
}
stop() {
	printf "Stopping gateway: "
	start-stop-daemon -K -q -p /var/run/gateway.pid
	[ $? = 0 ] && echo "OK" || echo "FAIL"
}
restart() {
	stop
	start
}

case "$1" in
  start)
  	start
	;;
  stop)
  	stop
	;;
  restart|reload)
  	restart
	;;
  *)
	echo "Usage: $0 {start|stop|restart}"
	exit 1
esac

exit $?